package com.njcb.ams.support.security.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.njcb.ams.factory.comm.DataBus;
import com.njcb.ams.support.config.AmsConfigUtil;
import com.njcb.ams.support.security.bo.LoginModel;
import com.njcb.ams.support.security.bo.SecurityUser;
import com.njcb.ams.support.security.config.AmsSecurityConfiguration;
import com.njcb.ams.util.AmsAssert;

@Component
public class CustomUserDetailsService implements UserDetailsService {

	static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

	@Override
	public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
		try {
			AmsSecurityConfiguration securityConfig = AmsConfigUtil.getBean(AmsSecurityConfiguration.class);
			AmsAssert.notNull(securityConfig,"未实现SecurityConfiguration接口配置");
			String authCode = "";
			if(LoginModel.AUTHCODE.equals(securityConfig.loginModel())){
				authCode = loginName;
			}
			SecurityUser securityUser = securityConfig.loadUserByUsername(loginName, authCode, DataBus.getAttributes(),true);
			AmsAssert.notNull(securityUser,"用户不能为空");
			AmsAssert.notNull(securityUser.getId(),"用户ID不能为空");
			AmsAssert.notNull(securityUser.getUserName(),"用户名不能为空");
			AmsAssert.notNull(securityUser.getBusiDate(), "交易日期不能为空");
			return securityUser;
		} catch (Exception e) {
			e.printStackTrace();
			throw new UsernameNotFoundException(e.getMessage());
		}
	}


}